package paylayer

import (
    "fmt"
	"time"
	"strconv"
	"dhfshop/models/misc"
	"encoding/json"
	"dhfshop/models/isv"
	"dhfshop/utils/math"
	"dhfshop/models/shopping"
	"github.com/astaxie/beego"
	"github.com/pkg/errors"
	 wxpay "wxsdk/wxpay/wxapp"
	 "wxsdk/wxpay/utils/pay"
	 "wxsdk/wxpay/utils/mapstruct"
)

type PayResponse struct {
	WxpayRsp   string   `json:"wxpay_rsp"`
	AlipayRsp  string   `json:"alipay_rsp"`
	BalanceRsp string   `json:"balance_rsp"`
    OrderId    string   `json:"order_id"`	
}

func OrderWxPay(appId,curOpenId string,storeId,orderId int64,acPay *isv.AcPayParams,amount float32)(rsp PayResponse,prepayId string, err error) {
	orderStr := strconv.FormatInt(orderId,10)
	body := "订单" + "[" + orderStr + "]"
	// 特约商户
	subAppId := ""
	subMchId := ""
	openID := ""
	subOpenID := ""
	if acPay.MchTypeId == 1 {
		openID = curOpenId
		subOpenID = ""
	}else if acPay.MchTypeId == 2 {
		subAppId = acPay.SubAppId
		subMchId = acPay.SubMchId
		openID = ""
		subOpenID = curOpenId
	} else {
	
	}
	wxPayNotify := beego.AppConfig.String("WXPayNotify") + "/public/wxpay/notify"
	attach := "ESHOP_ORDER_PAY"
	paymentStr := strconv.FormatInt(math.MultiTotalPriceInt(amount, 100), 10)
	profitSharing, err := GetShareFlag(acPay.SubAppId,storeId)
	beego.Debug("GetWxAppCfg profitSharing:", profitSharing)
	//
	m := &shopping.ValueOrder{OrderId:orderId,ProfitStatus:0}
	if profitSharing == "Y" {
	   m.ProfitStatus = 1
	}
	shopping.UpdateOrderProfit(m)
	//
	unifiedorderRsp, err := wxpay.Unifield(acPay.AppId,acPay.MchId,subAppId,subMchId,acPay.Appkey,
					wxPayNotify,orderStr,body,paymentStr,openID,subOpenID,attach,profitSharing)
	if err != nil {
		err = errors.Wrap(err, "Unifield... ")
		beego.Debug(err.Error())
		return 
	}
	wxRsp := misc.WxResponse{NonceStr:unifiedorderRsp.NonceStr,SignType:"MD5"}
	if acPay.MchTypeId == 1 {
		wxRsp.AppId = unifiedorderRsp.AppId
	} else if acPay.MchTypeId == 2 {
		wxRsp.AppId = unifiedorderRsp.SubAppId
	} else {
	
	}
	prepayId = unifiedorderRsp.PrepayId
	wxRsp.Package = "prepay_id=" + unifiedorderRsp.PrepayId
	wxRsp.TimeStamp = fmt.Sprintf("%s", time.Now().UTC())
	params := mapstruct.Struct2Map(wxRsp, "json")
	wxRsp.PaySign = payutils.MakeSign(params, acPay.Appkey)
	if tmpJson, err := json.Marshal(wxRsp); err == nil {
		rsp.WxpayRsp = string(tmpJson)
	}
	return
}

func ChargeWxPay(curOpenId,outTradeNo,body,attach string,acPay *isv.AcPayParams,amount float32)(rsp PayResponse,prepayId string,err error){
    // 特约商户
	subAppId := ""
	subMchId := ""
	openID := ""
	subOpenID := ""
	if acPay.MchTypeId == 1 {
		openID = curOpenId
		subOpenID = ""
	}else if acPay.MchTypeId == 2 {
		subAppId = acPay.SubAppId
		subMchId = acPay.SubMchId
		openID = ""
		subOpenID = curOpenId
	} else {
	
	}
	wxPayNotify := beego.AppConfig.String("WXPayNotify") + "/public/wxpay/notify"
	paymentStr := strconv.FormatInt(math.MultiTotalPriceInt(amount, 100), 10)
	unifiedorderRsp, err := wxpay.Unifield(acPay.AppId,acPay.MchId,subAppId,subMchId,acPay.Appkey,
					wxPayNotify,outTradeNo,body,paymentStr,openID,subOpenID,attach,"N")
	if err != nil {
		err = errors.Wrap(err, "Unifield... ")
		return 
	}
	wxRsp := misc.WxResponse{NonceStr:unifiedorderRsp.NonceStr,SignType:"MD5"}
	if acPay.MchTypeId == 1 {
		wxRsp.AppId = unifiedorderRsp.AppId
	} else if acPay.MchTypeId == 2 {
		wxRsp.AppId = unifiedorderRsp.SubAppId
	} else {
	
	}
	prepayId = unifiedorderRsp.PrepayId
	wxRsp.Package = "prepay_id=" + unifiedorderRsp.PrepayId
	wxRsp.TimeStamp = fmt.Sprintf("%s", time.Now().UTC())
	params := mapstruct.Struct2Map(wxRsp, "json")
	wxRsp.PaySign = payutils.MakeSign(params, acPay.Appkey)
	if tmpJson, err := json.Marshal(wxRsp); err == nil {
		rsp.WxpayRsp = string(tmpJson)
	}
	return
}

func CommonWxPay(curOpenId,orderId,body,kind string,acPay *isv.AcPayParams,amount float32)(rsp PayResponse,prepayId string, err error){
    wxPayNotify := beego.AppConfig.String("WXPayNotify") + "/public/wxpay/notify"
	paymentStr := strconv.FormatInt(math.MultiTotalPriceInt(amount, 100), 10)
	
	//商户参数
	openID := ""
	// 特约商户附加参数
	subAppId := ""
	subMchId := ""
	subOpenID := ""
	if acPay.MchTypeId == 1 {
		openID = curOpenId
		subOpenID = ""
	}else if acPay.MchTypeId == 2 {
		subAppId = acPay.SubAppId
		subMchId = acPay.SubMchId
		openID = ""
		subOpenID = curOpenId
	} else {
	
	}
	attach := kind		
	unifiedorderRsp, err := wxpay.Unifield(acPay.AppId,acPay.MchId,subAppId,subMchId,acPay.Appkey,
					wxPayNotify,orderId,body,paymentStr,openID,subOpenID,attach,"N")
	if err != nil {
		err = errors.Wrap(err, "Unifield... ")
		return 
	}
	wxRsp := misc.WxResponse{NonceStr:unifiedorderRsp.NonceStr,SignType:"MD5"}
	if acPay.MchTypeId == 1 {
		wxRsp.AppId = unifiedorderRsp.AppId
	} else if acPay.MchTypeId == 2 {
		wxRsp.AppId = unifiedorderRsp.SubAppId
	} else {
	
	}
	prepayId = unifiedorderRsp.PrepayId
	wxRsp.Package = "prepay_id=" + unifiedorderRsp.PrepayId
	wxRsp.TimeStamp = fmt.Sprintf("%s", time.Now().UTC())
	params := mapstruct.Struct2Map(wxRsp, "json")
	wxRsp.PaySign = payutils.MakeSign(params, acPay.Appkey)
	if tmpJson, err := json.Marshal(wxRsp); err == nil {
		rsp.WxpayRsp = string(tmpJson)
	}
	return
}

func GetShareFlag(appId string,storeId int64)(string, error){
	var profitSharing string = "N"
	cfg, err := misc.GetWxAppCfgByAppIdAndNameAndStoreId(appId,"CONFIG-FENZHANG",storeId); if err == nil {
	    var dat map[string]int
		dat = make(map[string]int)
		beego.Debug("cfg.Value:", cfg.Value)
        if err = json.Unmarshal([]byte(cfg.Value), &dat); err != nil {
		   return profitSharing, err
		}
	    for k, v := range dat {
		  storeIdStr := strconv.FormatInt(storeId, 10)
		  if storeIdStr == k && v == 1{
			 profitSharing = "Y"
		  }
	    }
	}
	return profitSharing, nil
}
